import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:ct_pa_majordomo/pages/mine/online_pay/state/online_pay_state.dart';
import 'package:ct_pa_majordomo/config/theme_vars.dart';
import 'package:ct_pa_majordomo/pages/commonApi.dart';
import 'package:ct_pa_majordomo/widgets/normal_scaffold/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:dio/dio.dart';
import 'package:permission_handler/permission_handler.dart';

class StorePhotoPage extends StatefulWidget {
  final OnlinePayState state;
  final VoidCallback onStateChanged;
  final bool isEnterprise;
  final bool isReadOnly;

  const StorePhotoPage({
    super.key,
    required this.state,
    required this.onStateChanged,
    this.isEnterprise = false,
    this.isReadOnly = false,
  });

  @override
  State<StorePhotoPage> createState() => _StorePhotoPageState();
}

class _StorePhotoPageState extends State<StorePhotoPage> {
  final _formKey = GlobalKey<FormState>();
  File? _storePhoto;
  final _picker = ImagePicker();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future<void> _takePhoto() async {
    try {
      final XFile? photo = await _picker.pickImage(source: ImageSource.camera);
      if (photo != null) {
        setState(() {
          _storePhoto = File(photo.path);
        });
      }
    } catch (e) {
      EasyLoading.showError('拍照失败');
    }
  }

  Future<void> _pickImage() async {
    try {
      final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
      if (image != null) {
        setState(() {
          _storePhoto = File(image.path);
        });
      }
    } catch (e) {
      EasyLoading.showError('选择图片失败');
    }
  }

  Future<void> _uploadImage() async {
    if (_storePhoto == null) {
      EasyLoading.showError('请先选择图片');
      return;
    }

    final fileSize = await _storePhoto!.length();
    if (fileSize > 1024 * 1024) {
      EasyLoading.showError('图片大小不能超过1MB');
      return;
    }

    try {
      EasyLoading.show(status: '上传中...');
      final formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(_storePhoto!.path),
      });
      final response = await commonApi.upload(formData);
      if (response['code'].toString() == '200' && response['data'] != null) {
        if (widget.isEnterprise) {
          widget.state.updateCompanyBusinessPlaceInfo(
            businessPlaceImg: response['data']['url'],
          );
        } else {
          widget.state.updatePersonBusinessPlaceInfo(
            businessPlaceImg: response['data']['url'],
          );
        }
      } else {
        EasyLoading.showError(response['msg'] ?? '上传失败');
      }
    } catch (e) {
      EasyLoading.showError('上传失败');
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> _saveForm() async {
    // 检查是否有经营场所照片
    String businessPlaceImg = widget.isEnterprise ? widget.state.company["businessPlaceImg"] : widget.state.person["businessPlaceImg"];
    if (businessPlaceImg.isEmpty && _storePhoto == null) {
      EasyLoading.showError('请上传经营场所照片');
      return;
    }

    EasyLoading.show(status: '保存中...');
    
    try {
      // 只有选择了新图片才需要上传
      if (_storePhoto != null) {
        await _uploadImage();
      }
      
      widget.onStateChanged();
      EasyLoading.dismiss();
      EasyLoading.showSuccess('保存成功');
      Navigator.pop(context);
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('保存失败：${e.toString()}');
    }
  }

  void _showImageSourceOptions() {
    bool isPickerActive = false;
    
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        title: const Text('选择图片来源'),
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _takePhoto().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("拍照操作错误: $e");
                });
              });
            },
            child: const Text('拍照'),
          ),
          CupertinoActionSheetAction(
            onPressed: () {
              if (isPickerActive) return;
              isPickerActive = true;
              Navigator.pop(context);
              
              Future.microtask(() {
                _pickImage().then((_) {
                  isPickerActive = false;
                }).catchError((e) {
                  isPickerActive = false;
                  print("选择图片操作错误: $e");
                });
              });
            },
            child: const Text('从相册选择'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
      ),
    );
  }

  Widget _renderStorePhoto() {
    String businessPlaceImg = widget.isEnterprise ? widget.state.company["businessPlaceImg"] : widget.state.person["businessPlaceImg"];
    if (businessPlaceImg.isNotEmpty || _storePhoto != null) {
      return businessPlaceImg.isNotEmpty
        ? Image.network(
        businessPlaceImg,
        fit: BoxFit.cover,
      )
        : Image.file(
        File(_storePhoto!.path),
        fit: BoxFit.cover,
      );
    }
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(
          Icons.add_a_photo,
          size: 48,
          color: Colors.grey[400],
        ),
        const SizedBox(height: 8),
        Text(
          '点击上传照片',
          style: TextStyle(
            color: Colors.grey[600],
            fontSize: 16,
          ),
        ),
      ],
    );
  }

  // 只读模式提示
  Widget _buildReadOnlyTip() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.blue.withOpacity(0.3)),
      ),
      child: Row(
        children: [
          Icon(
            Icons.info_outline,
            color: Colors.blue,
            size: 20,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              '当前信息为只读状态，无法修改',
              style: TextStyle(
                color: Colors.blue.shade700,
                fontSize: 14,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "经营场所照片",
      child: Form(
        key: _formKey,
        child: ListView(
          padding: const EdgeInsets.all(ThemeVars.paddingPage),
          children: [
            // 只读提示
            if (widget.isReadOnly) _buildReadOnlyTip(),
            Row(
              children: [
                Text(
                  '经营场所照片',
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Text(
                  ' *',
                  style: TextStyle(
                    color: Colors.red,
                    fontSize: 16,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            GestureDetector(
              onTap: widget.isReadOnly ? null : _showImageSourceOptions,
              child: Container(
                height: 200,
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: _renderStorePhoto(),
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '图片必须JPG/PNG/JPEG/BMP等类型文件，大小在1M以内',
              style: TextStyle(
                color: ThemeVars.colorTextSec,
                fontSize: 12,
              ),
            ),
            const SizedBox(height: 16),
            // 只有在非只读模式下才显示保存按钮
            if (!widget.isReadOnly)
              SizedBox(
                width: double.infinity,
                height: 44,
                child: ElevatedButton(
                  onPressed: _saveForm,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: ThemeVars.colorPrimary,
                    foregroundColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
} 